
//function Game(canvas,boardWidth,boardHeight,board,playerX,playerY,birdX,birdY)
function Game(canvas,boardFile,tip)
{

	this.canvas = canvas;
	this.ctx=canvas.getContext("2d");
	this.cwidth = canvas.width;
	this.cheight = canvas.height;
	
	this.isKeyDown= false;
	
	this.playerX = -1;
	this.playerY = -1;
	this.playerColor = "#000";
	this.birdX = -1;
	this.birdY = -1;
	this.birdColor = "#000";
	
//aktualna treść komunikatu, który ma się pojawić
	this.info = ["GET RDY!"];//["1","2","3","GET RDY!:)"];
	this.task = tip || "" ;
	this.playerDead = false;
	
//zmienna ustawiana na true, kiedy ma sie skonczyc gra w nastepnej petli
	this.end= false;
	
	this.gamePaused=false;
//potrzebne do wywlywania pol klasy w funkcjach przypisanych do window
	window.gameThis = this;

//zmienna do mierzenia czasu gry
	this.time= 0;
	this.timerInterval;

//wymiary planszy [kolumny x wiersze]
	this.boardWidth = 0;
	this.boardHeight = 0;
//ilosc  kluczy do zebrania. Jeśli będzie > 0 nie można przejść układu. Określa się sama dynamicznie na podstawie ilości kluczy na planszy.
	this.keysToGo = 0 ;
//tablica cyfr, na podstawie ktorych wczytywane są 'grafiki' i zachowania obiektów
/*
*0 -> powinien to być jakiś podstawowy element, po którym można bez problemu chodzić(podłoga)
*1 -> ściana
*2 -> zniszczalna przeszkoda
*3 -> śliskie podłoże
*4 -> przesuwalna przeszkoda
*5 -> klucz( bez zebranych wszystkich nie można przejść levelu )
*6 -> portal
*7 -> ogień(giniesz)
*8 -> zagadka
*9 -> ...
*/
	this.table;
	this.boardFile = boardFile ;
	
	this.objects = [];
//
//
//		
this._ = function( id )
{
	return document.getElementById( id );
}
//
//
//	
//dodaje obiekt do tablicy obiektow
this.addObject = function( ob )
{
	//var index = index || this.objects.length;
	this.objects[ this.objects.length ] = ob ;
}
//
//
//
//wypisuje do konsoli liste obiektow po kolei
this.listObjects = function()
{
	for( i in this.objects )
		console.log( i + " -> " + this.objects[i].name );
}

//
//
//
//timer liczacy czas gry
this.timer = function()
{
	if( !this.gamePaused )
	{
		this.time = parseInt(this.time) + 1;
		console.log( this.time );
	}
}

//
//
//	
//buduje plansze na podstawie pliku tekstowego z polami
this.buildTable = function(tab)
{
//walidacja szerokosc/wysokosci
	var boardHeight = tab.match(/\n/g);
	boardHeight = boardHeight.length + 1;
	var boardWidth = tab.indexOf("\n") - 1;
	
	if( boardWidth > 25 || boardWidth < 5 || boardHeight > 25 || boardHeight < 5 )
	{
		console.log("Error. Incorrect board size![MIN(5x5)MAX(25x25)]");
		return false;
	}
	
	this.birdX = boardWidth - 1;
	this.birdY = boardHeight - 1;
	
	tab = tab.replace(/\r?\n|\r/g,"");

//zapobieganie dziurom w tablicy pobieranej z pliku
	if( tab.length != boardWidth*boardHeight )
	{
		console.log("Error. The file is wrong.");
		return false;
	}
	
//prypisuje do pola klasy rekordy z pliku
	this.table= new Array(boardWidth);
	for(i=0;i<boardWidth;++i)
	{
		var counter=i;
		this.table[i] = new Array(boardHeight);
		for(k=0;k<boardHeight;++k,counter+=boardWidth)
		{
			this.table[i][k] = tab[counter] ;
			if( tab[counter] == "S" )
			{
				this.table[i][k]=0;
				this.playerX = i;
				this.playerY = k
			}
			else if( tab[counter] == "E" )
			{
				this.table[i][k]=0;
				this.birdX = i;
				this.birdY = k
			}
			else
			{
				if( tab[counter] == 5 )this.keysToGo = this.keysToGo + 1;
				this.table[i][k] = parseInt(tab[counter]) ;
			}
		}
	}
	if( this.playerX < 0 || this.playerY < 0 || this.birdX < 0 || this.birdY < 0 )
	{
		console.log("Error. Lack ov start/end.");
		return false;
	}
	
	this.boardWidth = boardWidth;
	this.boardHeight = boardHeight;
	
	this.gameLoop();
	//this.timerInterval = window.setInterval(this.timer,100);
	return true;
}
//
//
//		
	window.addEventListener("keydown",function(e)
	{
		var that = window.gameThis;
		//if(that.isKeyDown || that.gamePaused || this.previousButton == e.keyCode)return false;
		if( this.end )return false;
		if( e.which == 32 )
		{
			if( that.gamePaused && that.end )that.endGame();
			that.pauseGame();
			that.gameLoop();
			return false;
		}
		if( that.gamePaused )return false;
		switch(e.keyCode)
		{
			case 83://S
				that.movePlayer(2);
				//that.isKeyDown=true;
				that.gameLoop();
				break;
			case 65://A
				that.movePlayer(3);
				//that.isKeyDown=true;
				that.gameLoop();
				break;
			case 87://W
				that.movePlayer(0);
				//that.isKeyDown=true;
				that.gameLoop();
				break;
			case 68://D
				that.movePlayer(1);
				//that.isKeyDown=true;
				that.gameLoop();
				break;
		}
		//that.previousButton = e.keyCode;
		
	},true);
//
//
//		
	window.addEventListener("keyup",function(e){
		var that = window.gameThis;
		/*if(!that.isKeyDown)return false;
		if( e.keyCode == 68 || e.keyCode == 83 || e.keyCode == 65 || e.keyCode == 87 )
		{
			that.isKeyDown = false ;
			this.previousButton = 0;
		}
		*/
	});
//
//
//		
	this.gameLoop = function()
	{
		//
		if( this.playerX == this.birdX && this.playerY == this.birdY && this.keysToGo == 0 )
		{
			this.endGame("Koniec!");
			this.end=true;
		}
		this.draw();
	}
//
//
//		
	this.draw = function()
	{
		//o=this.objects[0].draw( this.ctx );
		
		this.ctx.clearRect(0,0,this.cwidth,this.cheight);
		this.ctx.strokeStyle="#FFF";
//ryswanie planszy
		for(i=0;i<this.boardWidth;++i)
		{
			for(k=0;k<this.boardHeight;++k)
			{
				this.ctx.lineWidth = 1;
				this.objects[ this.table[i][k] ].draw( this.ctx , this.cwidth/this.boardWidth*i,this.cheight/this.boardHeight*k,this.cwidth/this.boardWidth-1,this.cheight/this.boardHeight);
			}
		}
//rysowanie ptaszqa
		this.ctx.strokeStyle=this.birdColor;
		this.ctx.lineWidth = 3;
		this.ctx.beginPath();
		this.ctx.moveTo((this.birdX+.2)*this.cwidth/this.boardWidth,(this.birdY+.4)*this.cheight/this.boardHeight);
		this.ctx.lineTo((this.birdX+.4)*this.cwidth/this.boardWidth,(this.birdY+.8)*this.cheight/this.boardHeight);
		this.ctx.lineTo((this.birdX+.9)*this.cwidth/this.boardWidth,(this.birdY+.1)*this.cheight/this.boardHeight);
		this.ctx.stroke();
//rysowanie gracza
		this.ctx.strokeStyle=this.playerColor;
		this.ctx.lineWidth = 1.5;
		this.ctx.beginPath();
		var s = (this.cwidth > this.cheight) ? (this.cheight/this.cwidth) : (this.cwidth/this.cheight) ;
		var rad = (this.cwidth > this.cheight) ? this.cheight*s : this.cwidth*s ;
		this.ctx.arc((this.playerX+.5)*this.cwidth/this.boardWidth,(this.playerY+.5)*this.cheight/this.boardHeight,rad/20,0,6.5);
		this.ctx.stroke();
//rysowanie komunikatu(jesli jest)
		if( this.info.length > 0 )
		{
			this.ctx.beginPath();
			this.ctx.fillStyle="#000";
			this.ctx.fillRect(0,0,this.cwidth,this.cheight);
			this.ctx.fill();
			this.pauseGame(true);
			this.ctx.fillStyle="#FFF";
			this.ctx.font="20px Courier";
			this.ctx.textAlign="center";
			this.ctx.fillText(this.info[this.info.length-1],this.cwidth/2,this.cheight/3,this.cwidth);
			this.info.pop();
			
			this.ctx.font="10px Courier";
			this.ctx.textAlign="center";
			this.ctx.fillText("[SPACJA]",this.cwidth/2,this.cheight-15,this.cwidth);
		}
	}
//
//
//		
	this.startGame = function()
	{
		readFile(this);
	}
//
//
//
//pauzuje gre, sluzy do wypisywania komunikatow dla gracza
	this.pauseGame = function(force)
	{
		var force = force || "";
		if( force == "" )
		{
			this.gamePaused = !this.gamePaused;
			if( this.gamePaused )this.info[0] = "PAUZA" ;
		}
		else this.gamePaused = force;
		//if( this.gamePaused )window.clearInterval( this.timerInterval );
	//	else this.timerInterval = window.setInterval(this.timer,100);
	}
//
//
//		
	this.endGame = function(message)
	{
		var message = message || "" ;
		if( message.length > 0 )
		{
			this.info[0] = message;
			this.end = true;
		}
		else
		{
			//window.clearInterval( this.timerInterval );
			//tutaj jakiekolwiek operacje na zakonczenie gry(podliczanie punktow itp)
			//window.location.reload();
		}
		//
	}
//
//
//	
//wykonuje akcje(podstawowa akcja to przemieszczenie gracza) na polu docelowym
this.movePlayer = function( direction )
{
	switch( direction )
	{
		case 0:
			if( this.playerY-1 >= 0 && this.objects[ this.table[this.playerX][this.playerY-1] ].performAction( this.playerX,this.playerY-1,direction ) ) --this.playerY;
			break;
		case 1:
			if( this.playerX+1 < this.boardWidth && this.objects[ this.table[this.playerX+1][this.playerY] ].performAction( this.playerX+1,this.playerY,direction ) ) ++this.playerX;
			break;
		case 2:
			if( this.playerY+1 < this.boardHeight && this.objects[ this.table[this.playerX][this.playerY+1] ].performAction( this.playerX,this.playerY+1,direction ) ) ++this.playerY;
			break;
		case 3:
			if( this.playerX-1 >= 0 && this.objects[ this.table[this.playerX-1][this.playerY] ].performAction( this.playerX-1,this.playerY,direction ) ) --this.playerX;
			break;
	}
}
}
//
//
//	
function readFile(that)
{
	var http;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		http=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		http=new ActiveXObject("Microsoft.XMLHTTP");
	}
	http.onreadystatechange = function()
	{
		if(http.readyState == 4 )//&& http.status == 200)
		{
			that.buildTable(http.responseText);
		}
	}
	http.open("GET",that.boardFile,true);
	http.send();
}